package module.blog

class BlogController {

    def index = { redirect(action: "list", params: params) }

    def list = {

        //在页面上无法执行获取链接的方法,这是个奇怪的问题 //@明白了，在模板里面出错，但页面没有问题。模板是个特殊的东西
        //导航
        def nav = getLinks('导航')
        def friends = getLinks('友情链接')
        def articleClassList = ArticleClass.list()
        def articleInstanceList 

        if(params.id){
            articleInstanceList = Article.findAll('select a from Article a where a.articleClass='+params.id)
        }else{
            articleInstanceList = Article.list(params)
        }
       
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [articleInstanceList: articleInstanceList, articleInstanceTotal: Article.count(),nav:nav,friends:friends,articleClassList:articleClassList]
    }
    def show = {
        def articleInstance = Article.get(params.id)
        if(articleInstance){

            def nav = getLinks('导航')
            def friends = getLinks('友情链接')
            def articleClassList = ArticleClass.list()

            Article.withTransaction{
                articleInstance.viewTimes+=1
                if(articleInstance.save(flush:true)){
                    log.debug "view article : "+articleInstance
                }else{
                    log.warn "article viewtimes 更新失败 "+articleInstance.errors
                }
            }

            return [articleInstance:articleInstance,nav:nav,friends:friends,articleClassList:articleClassList]

        }else{
            render "no article or deleted!"
        }

        [articleInstance:articleInstance]
    }
    def login = {
        if(params.password){
            log.debug ' 用户登录 ' //C: '+servletContext.sysConfig+" P: "+params.password+" "+(servletContext.sysConfig.password==params.password)
            if(servletContext.sysConfig.password==params.password){
                log.debug 'login success'
                session.user = servletContext.sysConfig.userName
                redirect(controller:'valueConfig',action:'index')
            }else{
                log.debug 'password faile'
                flash.message="密码错误，请重新输入"
            }
        }
    }
    def logout = {
        session.invalidate()
        redirect(url:'/')
    }

    def getLinks(String catalog){
        def links = []
        def q=''
        if(catalog=='导航'){
            q='select l from Link l where l.catalog="导航" order by order asc'
        }else if(catalog=='友情链接'){
            q='select l from Link l where l.catalog="友情链接" order by order asc'
        }else{
            q='select l from Link l'
        }
        Link.findAll(q).each{
            def l=[:]
            l.title = it.title
            l.link = it.link
            links+=l
        }
        return links
    }
}
